package com.zxh.okretrofit.rxjava;


import android.app.Activity;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;

import com.zxh.okretrofit.exception.ApiException;
import com.zxh.okretrofit.exception.ExceptionEngine;
import com.zxh.okretrofit.listener.HttpOnPressListener;
import com.zxh.okretrofit.view.LoadingFragment;

import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import java.lang.ref.WeakReference;

/**
 * Created by zhangxuehui on 2018/3/7.
 */

public abstract class BaseSubscriber<T> implements Subscriber<T> {
    //    private WeakReference<Context> mContext;
    private boolean isShowLoading;
    private HttpOnPressListener mLoadingListener;

    public BaseSubscriber(Context context) {
//        mContext = new WeakReference<>(context);
    }


    public BaseSubscriber(Context context, boolean isShowLoading) {
//        mContext = new WeakReference<>(context);
        this.isShowLoading = isShowLoading;
    }


    @Override
    public void onSubscribe(Subscription subscription) {//
//        if (isShowLoading && getFragmentManager() != null) {
        if (isShowLoading) {
            mLoadingListener = LoadingFragment.newInstance();
            getLoadingFragment().onShow();
        }
    }

    @Override
    public void onNext(T t) {

    }

    @Override
    public void onError(Throwable e) {
        getLoadingFragment().onDismiss();
        if (e instanceof ApiException) {
            onError((ApiException) e);
        } else {
            onError(new ApiException(e, ExceptionEngine.UN_KNOWN_ERROR));
        }
    }

    @Override
    public void onComplete() {
        getLoadingFragment().onDismiss();
    }

    /**
     * 获取loadingfragment
     *
     * @return
     */
    private HttpOnPressListener getLoadingFragment() {
        if (mLoadingListener == null) {
            mLoadingListener = LoadingFragment.newInstance();
        }
        return mLoadingListener;
    }

//    /**
//     * 获取fragment管理器
//     *
//     * @return
//     */
//    private FragmentManager getFragmentManager() {
//        if (mContext.get() instanceof FragmentActivity) {
//            return ((FragmentActivity) mContext.get()).getSupportFragmentManager();
//        } else {
//            return null;
//        }
//    }

    /**
     * 网络请求失败
     *
     * @param e
     */
    protected abstract void onFail(ApiException e);

    /**
     * 网络请求失败
     *
     * @param t
     */
    protected abstract void onSuccess(T t);
}
